package com.jml.netty.手写dubbo.server.register;



import com.jml.netty.手写dubbo.common.RpcAnnotation;
import com.jml.netty.手写dubbo.server.ioc.RpContainer;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;


public class JmlRpcServer {

    /**
     * netty服务端host
     */
    private String host;
    /**
     * netty服务端端口号
     */
    private int port;

    private ZkServiceRegistration zkServiceRegistration;
    private RpcNettyServer rpcNettyServer;

    public JmlRpcServer(String host, int port) {
        this.host = host;
        this.port = port;
        zkServiceRegistration = new ZkServiceRegistration();
        rpcNettyServer = new RpcNettyServer();
    }

    // 需要发布服务
    public JmlRpcServer bind(Object object) throws UnsupportedEncodingException {
        // object 是 MemberService的实现类MemberServiceImpl
        // 1.需要将该接口注册到zk上
        RpcAnnotation declaredAnnotation = object.getClass().getDeclaredAnnotation(RpcAnnotation.class);
        //com.jml.netty.手写dubbo.api.MemberService，得到注解中类的全限定类名
        String sericeName = declaredAnnotation.value().getName();//双斜杆需要转义
        String addres = URLEncoder.encode("jmlrpc://" + host + ":" + port, "UTF-8");
        zkServiceRegistration.registr(sericeName, addres);
        // 2.将对应接口的实现类注册到容器中
        //    key是com.jml.netty.手写dubbo.api.MemberService， value是实现类
        RpContainer.put(sericeName, object);
        return this;
    }

    public void start() throws InterruptedException {
        // 2.启动一个netty服务器端监听消费者发送的消息
        rpcNettyServer.bind(port);
    }
}
